﻿using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using System;
using System.Text;
using System.Collections.Generic;
using AliyunAMQP;
using System.Threading;
using Microsoft.Extensions.Configuration;
using System.IO;

class Send
{
    public static void Main()
    {
        var configuration = new ConfigurationBuilder()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //可引入不同组件来支持xml、json、ini的配置文档
                             .Build();
        var aliyunConfig = AliyunUtils.GetConfig(configuration);

        var factory = new ConnectionFactory();
        /*接入点*/
        factory.HostName = aliyunConfig.HostName;
        /*阿里云的accessKey*/
        factory.UserName = aliyunConfig.UserName;
        /*阿里云的accessSecret*/
        factory.Password = aliyunConfig.Password;
        factory.VirtualHost = aliyunConfig.VirtualHost;
        /*默认端口*/
        factory.Port = aliyunConfig.Port;
        factory.AuthMechanisms = new List<IAuthMechanismFactory>() { new AliyunMechanismFactory()};
        factory.TopologyRecoveryEnabled = true;

        var connection = factory.CreateConnection();
        var channel = connection.CreateModel();

        channel.QueueDeclare(queue: aliyunConfig.QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
            
        while(true) {
            try {
                if(!connection.IsOpen) {
                    connection.Close();
                    connection = factory.CreateConnection();
                    channel = connection.CreateModel();
                }
                string message = Guid.NewGuid().ToString();
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: aliyunConfig.ExchangeName, routingKey: aliyunConfig.RoutingKey, basicProperties: null, body: body);
                Console.WriteLine(" [x] Sent {0}", message);
                Thread.Sleep(1000);
            } catch (BrokerUnreachableException e) {
                Thread.Sleep(3000);
                Console.WriteLine(e);
                continue;
            } catch (Exception e) {
                Console.WriteLine(e);
                continue;
            }
        }
    }
}
